<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Request AS UploadRequest;
use Validator;

class ApiController extends Controller
{
    /**
     * @api {post} /file UploudFile
     * @apiVersion 0.2.0
     * @apiName UploudFile
     * @apiGroup common
     * @apiPermission admin
     *
     * @apiDescription 文件上传
     *
     * @apiParam {String} file 上传文件.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {String} result 文件路径.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiSampleRequest http://192.168.1.120:82/api/file
     */
    public function upload(Request $request){
        if ($file = UploadRequest::file('file')) {
            
            $fileSize =  $file->getSize();
            if($fileSize > 2*1024*1024)
                return $this::jsonResponse(true,[],'文件需小于2M。'); 

            $fileExtension  = $file->getClientOriginalExtension();

            $input = $request->all();
            $fileExtension = empty($input["focus_jpg"])?$fileExtension:"jpg";
            $fileExtension = empty($input["focus_png"])?$fileExtension:"png";

            $folderType     = in_array($fileExtension, ["png", "jpg", "gif"])?"images":"files";

            $urlPath     = "/uploads/$folderType/".date("Ymd")."/";
            $serverPath  = $_SERVER["DOCUMENT_ROOT"].$urlPath;
            $fileName    = md5(date("Ymd").str_random(10)).'.'.$fileExtension;
            
            $file->move($serverPath, $fileName);
            
            if(!file_exists($serverPath.$fileName)){
                return $this::jsonResponse(true,'上传失败。');
            }

            return $this::jsonResponse(false,$urlPath.$fileName,'上传成功。');
            
        }else{
            return $this::jsonResponse(true,[],'无上传文件。'); 
        }
        
    }

}